<?php
class Cp_AuthController extends Pidguin_Controller_Cp_Action
{
	protected $_app = null;
	protected $_client = null;
	public function init()
	{
		$this->_app = Pidguin_Application::getInstance();
		$this->_client = Pidguin_Client::getInstance();
	}
	
	public function indexAction()
	{
		$this->_disableLayout();
		$request = clone $this->getRequest();
		$request->setModuleName('cp')->setControllerName('Index')->setActionName('index');
		if ($this->_client->isAccess($request) === true){
			$this->_redirect('/cp');
		}		
		$form = new Application_Form_Cp_Auth();
		$this->view->auth_form = $form;
	}
	
	public function loginAction()
	{
		$this->_disableView();		
		$form = new Application_Form_Cp_Auth();
		if ($this->getRequest()->isPost()) {
			if ($form->isValid($_POST)) {
				$values = $form->getValues();
				$values['password'] = sha1(md5($values['auth_password'], true));
				// find user				
				$model = Model_User::getInstance();
				$select = $model->select();
				$select->where($model->getAdapter()->quoteInto('login = ?', $values['auth_login']));
				$select->where($model->getAdapter()->quoteInto('password = ?', $values['password']));
				$user = $model->fetchRow($select);
				if (!$user) {
					$response = $this->_helper->json(array('error' => array('user' => array('notUser' => 'Пользователь не найден'))));
					$this->getResponse()->setBody($response);
				}
				// авторизовываем
				$client = Pidguin_Client::getInstance();
				if ($client->authorize($user, true)){
					$this->_helper->json(array('redirect' => '/cp'));
				} else {
					$response = $this->_helper->json(array('error' => array('user' => array('access_denied' => 'Извините, у Вас нет доступа к Панели управления'))));
					$this->getResponse()->setBody($response);
				}
			} else {
				$response = $this->_helper->json(array('error' => $form->getMessages()));
				$this->getResponse()->setBody($response);
			}
		}
	}
	
	public function logoutAction()
	{
		$this->_disableView();
		
		$this->_client->logout();
		
		$this->_redirect('/cp/auth');
	}
}
